﻿using System;
using System.Security.Permissions;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.Workflows
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class StartWFEventReceiver : SPItemEventReceiver
    {         
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            if (properties.ListTitle.ToLower() == Constants.ChangingListTitle)
            {
                StartWorkflow(properties.Web.Site, properties.List, properties.ListItem);
            }
        }

        /// <summary>
        /// An item was updated
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            if (properties.ListTitle.ToLower() == Constants.ChangingListTitle)
            {
                StartWorkflow(properties.Web.Site, properties.List, properties.ListItem);
            }
        }
        
        /// <summary>
        /// Add assignees to workflow and start it immediatelly 
        /// </summary>
        /// <param name="siteId">Current site Id</param>
        /// <param name="webId">Current web Id</param>
        /// <param name="changingList">List where the workflow is associated</param>
        /// <param name="item">Item where the workflow will be started</param>
        private void StartWorkflow(SPSite site, SPList changingList, SPListItem item)
        {
            if (item != null && !SPHelper.IsWorkFlowAssociatedToItem(item))
            {
                if (item[Constants.FirstApproverField] != null)
                {
                    List<SPFieldUserValue> users = new List<SPFieldUserValue>();
                    users.Add(GetSPUser(item, Constants.FirstApproverField));
                    if (item[Constants.SecondApproverField] != null)
                    {
                        users.Add(GetSPUser(item, Constants.SecondApproverField));
                    }
                    SPWorkflowAssociation workflowAssociation = changingList.WorkflowAssociations[0];                    
                    workflowAssociation.AssociationData = SPHelper.AssignUserToWorkflow(workflowAssociation.AssociationData, users);
                    item[Constants.CurrentApproverField] = item[Constants.FirstApproverField];
                    item.Update();
                    SPWorkflow wf = site.WorkflowManager.StartWorkflow(item, workflowAssociation, workflowAssociation.AssociationData, true);                    
                }
            }
        }

        /// <summary>
        /// Get the SPUser object from Item 
        /// </summary>
        /// <param name="item">Item from the list</param>
        /// <param name="fieldName">field name containing the user</param>
        /// <returns>SPUser objectof the specified item</returns>
        private SPFieldUserValue GetSPUser(SPListItem item, string fieldName)
        {           
            SPFieldUser field = item.Fields.GetField(fieldName) as SPFieldUser;
            if (field != null && item[fieldName] != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue;
                }
            }
            return null;
        } 
    }
}
